package com.zelin.model3;

import sun.reflect.generics.scope.Scope;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP通信:
 * 服务端
 */
public class TcpServer {
    public static void main(String[] args) {
        ServerSocket server = null;
        Socket socket = null;

        //定义服务端对象,并指定接入的端口号
        try {
            server = new ServerSocket(6666);
            System.out.println("服务端已创建!");
            /**
             * 如何实现多个客户端访问服务端,互相不影响?
             * 使用多线程,继承Thread,创建线程LoginThread,客户端通过线程访问服务端
             */
            while (true) {
                //等待客户端接入,接入后返回一个客户端的对象
                socket = server.accept();
                System.out.println("客户端已接入");

                LoginThread loginThread=new LoginThread(socket);
                loginThread.start();
            }

        } catch (IOException  e) {
            e.printStackTrace();
        } finally {
            try {
                assert server != null;
                assert socket != null;
                socket.close();
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
